package com.marmot.cloud.framework.utils;


import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 【工具】驼峰工具类
 * 
 * @author shenpeng
 *
 */
public class CamelUtil {
	private static final char UNDERLINE = '_';
	private static final Pattern PATTERN_UNDERLINE = Pattern.compile("_");
	private static Matcher matcher = null;

	/**
	 * 驼峰格式字符串转换为下划线格式字符串
	 * 
	 * @param param
	 * @return
	 */
	public static String camelToUnderline(String param) {
		if (param == null || "".equals(param.trim())) {
			return "";
		}
		int len = param.length();
		StringBuilder sb = new StringBuilder(len);
		for (int i = 0; i < len; i++) {
			char c = param.charAt(i);
			if (Character.isUpperCase(c)) {
				sb.append(UNDERLINE);
				sb.append(Character.toLowerCase(c));
			} else {
				sb.append(c);
			}
		}
		return sb.toString();
	}

	/**
	 * 下划线格式字符串转换为驼峰格式字符串
	 * 
	 * @param param
	 *            下划线格式字符串
	 * @return 返回转换后的字符串
	 */
	public static String underlineToCamel(String param) {
		if (param == null || "".equals(param.trim())) {
			return "";
		}
		int len = param.length();
		StringBuilder sb = new StringBuilder(len);
		for (int i = 0; i < len; i++) {
			char c = param.charAt(i);
			if (c == UNDERLINE) {
				if (++i < len) {
					sb.append(Character.toUpperCase(param.charAt(i)));
				}
			} else {
				sb.append(c);
			}
		}
		return sb.toString();
	}

	/**
	 * 下划线格式字符串转换为驼峰格式字符串2
	 * 
	 * @param param
	 *            下划线格式字符串
	 * @return 返回转换后的字符串
	 */
	public static String underlineToCamel2(String param) {
		if (param == null || "".equals(param.trim())) {
			return "";
		}
		StringBuilder sb = new StringBuilder(param);
		matcher = PATTERN_UNDERLINE.matcher(param);
		int i = 0;
		while (matcher.find()) {
			int position = matcher.end() - (i++);
			sb.replace(position - 1, position + 1, sb.substring(position, position + 1).toUpperCase());
		}
		return sb.toString();
	}

	public static void main(String[] args) {
		String appName = "app_version_fld";
		System.out.println(underlineToCamel(appName));
		System.out.println(underlineToCamel2(appName));
		appName = "appVersionFld";
		System.out.println(camelToUnderline(appName));

	}
}
